package com.taptech.doufu.ui.viewholder.personalcenter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.taptech.doufu.ui.activity.UserDetailActivity;
import com.taptech.doufu.ui.view.personalcenter.NewMyCollectView;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.NewOthersPersonalActivity;
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity;
import com.taptech.doufu.bean.MineAbstractBean;
import com.taptech.doufu.bean.MineNovelBean;
import com.taptech.doufu.bean.PersonalNoteBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.drawcircle.BaseRecyclerViewViewHolder;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.view.personalcenter.OldPersonalNoteViewHolder;
import com.taptech.doufu.services.PersonalNoteService;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.GlideUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.ui.view.DiaobaoTextView;

/**
 * Created by lsy on 2015/6/29.
 */

public class PersonalNoteViewHolder<T extends PersonalNoteBean> extends BaseRecyclerViewViewHolder implements View.OnClickListener, View.OnLongClickListener
{

    static public final int TWO_SPAN_DISPLAY = 2;

    public static final int TEXT_DES_MAX_LENGTH = 30;


    Context mContext;
    /**
     * UI控件
     */
    public RelativeLayout backGroundView;
    public LinearLayout mContentBackgroudView;
    public ImageView mUserHeadImg, mUserMedalImg;
    //用户名和发表时间
    public TextView mUserName, mUserUgcTime;
    //内容标题
    public TextView mNoteTitle;
    //图片及数目
    public SimpleDraweeView mContentImgeView;
    public TextView mContentImgNum;
    public DiaobaoTextView mContentTextView;
    public LinearLayout mContentImgNumLayout;
    //浏览、献菊、评论数
    public TextView mReadCount, mFlowerCount, mCommentCount, mDeleteBtn;
    // gif标志
    public ImageView mGifSignIcon;

    private ImageView novel_end_iv, novel_continue_iv;
    private TextView novel_content_textview;
    private View bottom_layout;
    LinearLayout flowerLayout, commentLayout, scanCountLayout;
    /**
     * 数据
     */
    protected T contentBean;
    protected Handler mHandler;

    public PersonalNoteViewHolder(View itemView, Context context)
    {

        super(context, itemView);
        mContext = context;
        backGroundView = (RelativeLayout) itemView.findViewById(R.id.note_backgroud_layout);
        mContentBackgroudView = (LinearLayout) itemView.findViewById(R.id.home_item_subject_image);

        mUserHeadImg = (ImageView) itemView.findViewById(R.id.home_item_subject_authorimg);
        if (mUserHeadImg != null)
        {
            mUserHeadImg.setOnClickListener(this);
        }
        mUserMedalImg = (ImageView) itemView.findViewById(R.id.home_item_subject_medal);
        mUserName = (TextView) itemView.findViewById(R.id.home_item_subject_username);
        mUserUgcTime = (TextView) itemView.findViewById(R.id.home_item_subject_time);
        mCircleSource = (TextView) itemView.findViewById(R.id.home_item_subject_circle_source);
        mNoteTitle = (TextView) itemView.findViewById(R.id.personalnote_item_title_textview);
        mContentImgeView = (SimpleDraweeView) itemView.findViewById(R.id.personal_note_image);
        mContentTextView = (DiaobaoTextView) itemView.findViewById(R.id.personal_item_content_textview);

        mContentImgNum = (TextView) itemView.findViewById(R.id.content_img_num);
        mContentImgNumLayout = (LinearLayout) itemView.findViewById(R.id.content_img_num_layout);
        mReadCount = (TextView) itemView.findViewById(R.id.home_item_subject_readtimes);
        mFlowerCount = (TextView) itemView.findViewById(R.id.home_contents_item_flower_counts);
        mCommentCount = (TextView) itemView.findViewById(R.id.home_item_subject_circle_chatcount);
        mDeleteBtn = (TextView) itemView.findViewById(R.id.delete_item_btn);
        mGifSignIcon = (ImageView) itemView.findViewById(R.id.image_gif_sign_icon);
        rankImageView = (ImageView) itemView.findViewById(R.id.home_rank_position);

        // novel_continue_iv = (ImageView) itemView.findViewById(R.id.novel_status_continue_iv);
        // novel_end_iv = (ImageView) itemView.findViewById(R.id.novel_status_end_iv);
        novel_content_textview = (TextView) itemView.findViewById(R.id.novel_content_textview);
        bottom_layout = itemView.findViewById(R.id.home_item_subject_bottom_layout);
        flowerLayout = (LinearLayout) itemView.findViewById(R.id.home_contents_item_praise_layout);
        commentLayout = (LinearLayout) itemView.findViewById(R.id.item_comment_layout);
        scanCountLayout = (LinearLayout) itemView.findViewById(R.id.scan_count_layout);
    }

    private void setBottomLayoutVisiable(boolean visiable)
    {
        flowerLayout.setVisibility(View.GONE);
        if (visiable)
        {
//            flowerLayout.setVisibility(View.VISIBLE);
            commentLayout.setVisibility(View.VISIBLE);
            scanCountLayout.setVisibility(View.VISIBLE);
        } else
        {
//            flowerLayout.setVisibility(View.GONE);
            commentLayout.setVisibility(View.GONE);
            scanCountLayout.setVisibility(View.GONE);
        }

    }


    public void setViewHolderChildViewContent(T bean, int position)
    {

        if (mDeleteBtn != null)
        {
            mDeleteBtn.setOnClickListener(this);
        }

        contentBean = bean;
        if (bean == null)
        {
            return;
        }
        mPosition = position;
        handleChildViewDisplay(contentBean);

    }

    public void setHandler(Handler handler)
    {
        mHandler = handler;
    }

    @Override
    public void onClick(View view)
    {


        switch (view.getId())
        {
            case R.id.home_item_subject_authorimg:
                if (contentBean != null && contentBean.getUser_id() != null && !AccountService.getInstance().isUserSelf(contentBean.getUser_id())) {
                    UserDetailActivity.Companion.startActivity(mContext,contentBean.getUser_id());
                }
                break;
            case R.id.delete_item_btn:
                if ((contentBean.getSpecialType() & SPECIAL_TYPE_COLLECT) == SPECIAL_TYPE_COLLECT)
                {
                    Message message = new Message();
                    message.what = NewMyCollectView.DEL_COLLECT_ITEM_COMMAND;
                    Bundle bundle = new Bundle();
                    bundle.putString("id", contentBean.getId());
                    bundle.putInt("position", mPosition);
                    bundle.putString(Constant.OBJECT_TYPE, contentBean.getObject_type());
                    message.setData(bundle);
                    if (mHandler != null)
                    {
                        mHandler.sendMessage(message);
                    }
                } else
                {
                    if (AccountService.getInstance().isUserSelf(contentBean.getUser_id()))
                    {
                        Message message = new Message();
                        message.what = BaseAdapterViewHolder.DELETE_NOTE_ITEM;
                        Bundle bundle = new Bundle();
                        bundle.putString("id", contentBean.getId());
                        bundle.putInt("position", mPosition);
                        bundle.putString(Constant.OBJECT_TYPE, contentBean.getObject_type());
                        message.setData(bundle);
                        if (mHandler != null)
                        {
                            mHandler.sendMessage(message);
                        }

                    }
                }

                break;
            default:
                int target_type = DiaobaoUtil.String2Int(contentBean.getTarget_type());
                switch (target_type)
                {
                    case OldPersonalNoteViewHolder.TARGET_TYPE_NOTE_TO_NOVEL_DES:
                        Intent temp_intent = new Intent(mContext, NovelSectionDetailsActivity.class);
                        temp_intent.putExtra(Constant.ARTICLE_NOVELID, contentBean.getObject_id());//topic id
                        temp_intent.putExtra(Constant.ARTICLE_ID, contentBean.getSubobject_id());// details id
                        temp_intent.putExtra(Constant.IS_SELF, true);
                        mContext.startActivity(temp_intent);
                        break;
                    default:
                        PersonalNoteService.getInstance().enterPersonalNoteDesActivity(mContext, contentBean.getId(), contentBean.getObject_type());
                        break;
                }
                break;
        }
    }

    @Override

    public boolean onLongClick(View view)
    {
        switch (view.getId())
        {
            case R.id.home_item_subject_image:
                if ((contentBean.getSpecialType() & SPECIAL_TYPE_COLLECT) == SPECIAL_TYPE_COLLECT)
                {
                    Message message = new Message();
                    message.what = NewMyCollectView.DEL_COLLECT_ITEM_COMMAND;
                    Bundle bundle = new Bundle();
                    bundle.putString("id", contentBean.getId());
                    bundle.putInt("position", mPosition);
                    bundle.putString(Constant.OBJECT_TYPE, contentBean.getObject_type());
                    message.setData(bundle);
                    if (mHandler != null)
                    {
                        mHandler.sendMessage(message);
                    }
                } else
                {
                    if (AccountService.getInstance().isUserSelf(contentBean.getUser_id()))
                    {
                        Message message = new Message();
                        message.what = BaseAdapterViewHolder.DELETE_NOTE_ITEM;
                        Bundle bundle = new Bundle();
                        bundle.putString("id", contentBean.getId());
                        bundle.putInt("position", mPosition);
                        bundle.putString(Constant.OBJECT_TYPE, contentBean.getObject_type());
                        message.setData(bundle);
                        if (mHandler != null)
                        {
                            mHandler.sendMessage(message);
                        }
                    }
                }
                break;
            default:

                break;
        }
        return true;
    }

    @Override
    public void setViewHolderChildViewContent(MineAbstractBean bean, int position)
    {


        contentBean = (T) bean;
        if (bean == null)
        {
            return;
        }
        mPosition = position;
        handleChildViewDisplay(contentBean);


    }


    private void handleChildViewDisplay(final T contentBean)
    {
        mContentBackgroudView.setOnClickListener(this);
        mContentBackgroudView.setOnLongClickListener(this);
        mContentTextView.setOnClickListener(this);
        mContentTextView.setOnLongClickListener(this);
        if (mDeleteBtn != null)
        {
            mDeleteBtn.setOnClickListener(this);
        }

        //头像及用户名
        mUserHeadImg.setImageResource(R.drawable.default_user_portrait);
        if (contentBean.getUser() != null)
        {
            GlideUtil.displayCircleImage(mUserHeadImg, contentBean.getUser().getIcon());
            DiaobaoUtil.setMedalImgView(contentBean.getUser().getMedal(), mUserMedalImg);
            mUserName.setText(contentBean.getUser().getName());
        }
        if (contentBean.getCreated_at() != null)
        {
            if (contentBean.getCreated_at().contains(" "))
            {
                mUserUgcTime.setText(contentBean.getCreated_at());
            } else
            {
                mUserUgcTime.setText(DiaobaoUtil.seconds2TimeString(Long.parseLong(contentBean.getCreated_at())));
            }
        }
        if (contentBean.getObject_type() != null)
        {
            if (contentBean.getObject_type().equals(PersonalNoteService.OBJECT_TYPE_NOTE))
            {
                mCircleSource.setText("");
            } else if (contentBean.getObject_type().equals(PersonalNoteService.OBJECT_TYPE_DRAW))
            {
                if (contentBean.getDrawing_type().equals("1"))
                {
                    mCircleSource.setText("插画");
                } else
                {
                    mCircleSource.setText("漫画");
                }
            } else if (contentBean.getObject_type().equals(PersonalNoteService.OBJECT_TYPE_COSER))
            {
                mCircleSource.setText("COS");
            }
        }
        if (contentBean.getTitle() != null)
        {
            mNoteTitle.setText(contentBean.getTitle());
            if (contentBean.getTitle().equals(""))
            {
                mNoteTitle.setVisibility(View.GONE);
            } else
            {
                mNoteTitle.setVisibility(View.VISIBLE);
            }
        } else
        {
            mNoteTitle.setVisibility(View.GONE);
        }

        if (contentBean.getContent() != null)
        {
            mContentTextView.setClickMode((byte) (DiaobaoTextView.AtClickEnable | DiaobaoTextView.LinkClickEnable));

            mContentTextView.setDiaobaoText(contentBean.getContent() + " ", PersonalNoteViewHolder.TEXT_DES_MAX_LENGTH);
            if (contentBean.getContent().equals(""))
            {
                mContentTextView.setVisibility(View.GONE);
            } else
            {
                mContentTextView.setVisibility(View.VISIBLE);
            }
        } else
        {
            mContentTextView.setVisibility(View.GONE);
        }
        // 内容是否包含图片
        if (contentBean.getCover() != null)
        {
            mContentImgeView.setVisibility(View.VISIBLE);
            String headUrl = "http://imgold2.doufu.la/";
            String imgUrl = headUrl + contentBean.getCover().getCrop_path();
            int cropImgWidth = Integer.valueOf(contentBean.getCover().getCrop_width());
            int cropImgHeight = Integer.valueOf(contentBean.getCover().getCrop_height());
            float imageAspetctRatio = cropImgWidth / (float) cropImgHeight;
            if (imageAspetctRatio < 1)
            {
                imageAspetctRatio = 1;
            }
            mContentImgeView.setBackgroundResource(R.drawable.biankuang_no_image);
            ImageManager.loadImage(mContentImgeView, imgUrl, imageAspetctRatio, new BaseControllerListener<ImageInfo>()
            {
                @Override
                public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable)
                {
                    super.onFinalImageSet(id, imageInfo, animatable);
                    if (contentBean.getImages().length > 1)
                    {
                        mContentImgNumLayout.setVisibility(View.VISIBLE);
                        mContentImgNum.setText(contentBean.getImages().length + "P");
                    } else
                    {
                        mContentImgNumLayout.setVisibility(View.GONE);
                    }
                }
            });
            // 如果是gif则显示标志
            if (DiaobaoUtil.isImageUrlGif(imgUrl))
            {
                mGifSignIcon.setVisibility(View.VISIBLE);
            } else
            {
                mGifSignIcon.setVisibility(View.GONE);
            }
        } else
        {
            mContentImgeView.setVisibility(View.GONE);
            mContentImgNumLayout.setVisibility(View.GONE);
        }

        if (contentBean.getRead_times() != null)
        {

            mReadCount.setText(contentBean.getRead_times());
        }
        if (contentBean.getFlower_count() != null)
        {
            mFlowerCount.setText(contentBean.getFlower_count());
        }
        if (contentBean.getComment_times() != null)
        {
            mCommentCount.setText(contentBean.getComment_times());
        }
        if (AccountService.getInstance().isUserSelf(contentBean.getUser_id()) && contentBean.getSpecialType() == SPECIAL_TYPE_PERSONAL_DELETE)
        {
            mDeleteBtn.setVisibility(View.VISIBLE);
            if (contentBean.getSpecialType() == SPECIAL_TYPE_COLLECT)
            {
                mDeleteBtn.setText("取消收藏");
            } else
            {
                mDeleteBtn.setText("删除");
            }
        } else
        {
            mDeleteBtn.setVisibility(View.GONE);
        }


        if (contentBean.isRank_flag())
        {
            setRankImageView(mPosition + 1);
        } else if (rankImageView != null)
        {
            rankImageView.setVisibility(View.GONE);
        }

        //如果是小说更新
        if (contentBean.getNovel() != null && DiaobaoUtil.String2Int(contentBean.getTarget_type()) == OldPersonalNoteViewHolder.TARGET_TYPE_NOTE_TO_NOVEL_DES)
        {
            MineNovelBean novelBean = contentBean.getNovel();
            setBottomLayoutVisiable(false);
            novel_content_textview.setVisibility(View.VISIBLE);
            mCircleSource.setText("小说");
            if (novelBean.getFinished() != null)
            {
                mNoteTitle.setText(novelBean.getTitle());
            }
            mContentTextView.setText(contentBean.getTitle());
            novel_content_textview.setText(contentBean.getContent());
            if (novelBean.getFinished() != null)
            {


                if (novelBean.getFinished().equals("0"))
                {
                  /*  novel_end_iv.setVisibility(View.GONE);
                    novel_continue_iv.setVisibility(View.VISIBLE);*/
                    Drawable drawable1 = mContext.getResources().getDrawable(R.drawable.icon_novel_continue);
                    drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                    mNoteTitle.setCompoundDrawables(null, null, drawable1, null);
                } else
                {
                   /* novel_continue_iv.setVisibility(View.GONE);
                    novel_end_iv.setVisibility(View.VISIBLE);*/
                    Drawable drawable1 = mContext.getResources().getDrawable(R.drawable.icon_novel_end);
                    drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                    mNoteTitle.setCompoundDrawables(null, null, drawable1, null);//
                }

            }
            if (contentBean.getCreated_at().contains(" "))
            {

                mUserUgcTime.setText(contentBean.getCreated_at());
            } else
            {
                mUserUgcTime.setText("更新章节：" + DiaobaoUtil.seconds2TimeString(Long.parseLong(contentBean.getCreated_at())));
            }
        } else
        {
            mNoteTitle.setCompoundDrawables(null, null, null, null);
            novel_content_textview.setVisibility(View.GONE);
            setBottomLayoutVisiable(true);
        }
        handleSpecialType(mPosition);
    }

    private void handleSpecialType(int position)
    {
        if (contentBean != null)
        {
            if ((contentBean.getSpecialType() & TWO_SPAN_DISPLAY) == TWO_SPAN_DISPLAY)
            {
                backGroundView.setPadding(ScreenUtil2.dip2px(3), ScreenUtil2.dip2px(5), ScreenUtil2.dip2px(3), 0);
                mCircleSource.setVisibility(View.GONE);
                mContentTextView.setVisibility(View.GONE);
                mNoteTitle.setTextSize(14);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentImgNumLayout.getLayoutParams();
                layoutParams.setMargins(0, ScreenUtil2.dip2px(4), ScreenUtil2.dip2px(4), 0);
                mContentImgNumLayout.setLayoutParams(layoutParams);
            } else
            {
                backGroundView.setPadding(ScreenUtil2.dip2px(6), ScreenUtil2.dip2px(5), ScreenUtil2.dip2px(6), 0);
                mCircleSource.setVisibility(View.VISIBLE);
                mContentTextView.setVisibility(View.VISIBLE);
                mNoteTitle.setTextSize(18);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mContentImgNumLayout.getLayoutParams();
                layoutParams.setMargins(0, ScreenUtil2.dip2px(10), ScreenUtil2.dip2px(8), 0);
                mContentImgNumLayout.setLayoutParams(layoutParams);
            }
        }
    }

}
